//
//  WJUser.m
//  Wujin
//
//  Created by 东 on 16/12/10.
//  Copyright © 2016年 dong. All rights reserved.
//

#import "WJUser.h"

@implementation WJUser

+ (instancetype)user
{
    static WJUser *user = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        user = [[self alloc] init];
    });
    return user;
}


+ (void)loginWithPhone:(NSString *)phone password:(NSString *)password result:(WJUserResult)result
{
    
    NSString *url = F(@"%@User/login", BASEURL);
    
    NSDictionary *dict = @{
                           @"phone" :phone,
                           @"password" : password
                           };
    
    [FSServer requestWithTarget:url param:dict result:^(id responseObject, NSError *error) {
        if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            if ([responseObject[@"flag"] intValue]==1)
            {
                WJUser *user = [WJUser user];
                
                user = [user initWithParam:responseObject[@"data"]];
                user.login = YES;
                
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                
                [defaults setObject:phone forKey:@"Phone"];
                [defaults setObject:password forKey:@"Password"];

                
                [[NSNotificationCenter defaultCenter] postNotificationName:USER_LOGIN object:nil];
                
                if (result)
                {
                    result(user, nil);
                }
            }
            else if ([responseObject[@"flag"] intValue]==0)
            {
                WJUser *user = [WJUser user];
                user.login = NO;
                NSError *flagerror = [NSError errorWithDomain:@"nil" code:0 userInfo:@{@"msg" :responseObject[@"msg"]}];
                if (result)
                {
                    result(nil, flagerror);
                }
            }
        }
    }];
}

- (instancetype)initWithParam:(NSDictionary *)param
{
    WJUser *user = [WJUser user];
    
    user.phone      = [self avoidNSNull:param[@"phone"]];
    user.address    = [self avoidNSNull:param[@"address"]];
    user.pre_phone  = [self avoidNSNull:param[@"pre_phone"]];
    user.qq         = [self avoidNSNull:param[@"qq"]];
    user.wechat     = [self avoidNSNull:param[@"wechat"]];
    user.user_id    = [self avoidNSNull:param[@"user_id"]];
    user.name       = [self avoidNSNull:param[@"name"]];
    return user;
}

- (NSString *)avoidNSNull:(id)obj
{
   return [obj isKindOfClass:[NSNull class]] ? @"" : obj;
}

@end
